﻿#region License
// Copyright (c) 2009 Shengmin Zhang
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Web;
using System.IO;
using System.Text;
using System.Collections.Specialized;
using System.IO.Compression;

using Apprender.Web;
using Apprender.Compression;
using Apprender.Extensions.Methods;


namespace Apprender.Utilities
{
    public static class UHttp
    {
        public static string GetHeaderValue(NameValueCollection headers, string key)
        {


            for (int i = 0; i < headers.Count; i++)
            {
                if (string.Equals(headers.GetKey(i), key, StringComparison.OrdinalIgnoreCase))
                {
                    return headers.Get(i);
                }
            }

            return string.Empty;
        }

        public static CompressionEncoding GetCompressionEncoding(HttpRequest request)
        {
            return GetCompressionEncoding(request.Headers);
        }

        public static CompressionEncoding GetCompressionEncoding(NameValueCollection headers)
        {
            return GetCompressionEncoding(headers.GetValue("Accept-Encoding"));
        }

        public static CompressionEncoding GetCompressionEncoding(string value)
        {
            CompressionEncoding encoding = CompressionEncoding.None;
            if (value.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                encoding = CompressionEncoding.GZip;
            }
            if (value.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                //encoding = encoding | CompressionEncoding.Deflate;
            }
            return encoding;
        }


        public static CompressionEncoding GetCompressionEncoding2(string value)
        {
            CompressionEncoding encoding = CompressionEncoding.None;
            //var value = GetHeaderValue(request.Headers, "Accept-Encoding");

            var values = value.Split(',');


            for (int i = 0; i < values.Length; i++)
            {
                string val = values[i];
                if (val[0] == 'g' &&
                    val[1] == 'z' &&
                    val[2] == 'i' &&
                    val[3] == 'p')
                {
                    encoding = encoding | CompressionEncoding.GZip;
                }
                else if (
                    val[0] == 'd' &&
                    val[1] == 'e' &&
                    val[2] == 'f' &&
                    val[3] == 'l' &&
                    val[4] == 'a' &&
                    val[5] == 't' &&
                    val[6] == 'e')
                {
                    //encoding = encoding | CompressionEncoding.Deflate;
                }

                /*
                if (string.Equals(values[i], "gzip"))
                {
                    encoding = encoding | CompressionEncoding.GZip;
                }
                else if (string.Equals(values[i], "deflate"))
                {
                    encoding = encoding | CompressionEncoding.Deflate;
                }
                 * */
            }




            /*
            var headers = request.Headers;
            for (int i = 0; i < headers.Count; i++)
            {                
                string h = headers.GetKey(i);                
                if (h.Length == 15 &&
                    h[0] == 'A' &&
                    h[1] == 'c' &&
                    h[2] == 'c' &&
                    h[3] == 'e' &&
                    h[4] == 'p' &&
                    h[5] == 't' &&
                    h[6] == '-' &&
                    h[7] == 'E' &&
                    h[8] == 'n' &&
                    h[9] == 'c' &&
                    h[10] == 'o' &&
                    h[11] == 'd' &&
                    h[12] == 'i' &&
                    h[13] == 'n' &&
                    h[14] == 'g')
                {

                    string a = headers.Get(i);
                    if (a.Length >= 4)
                    {
                        if (a[0] == 'g' &&
                            a[1] == 'z' &&
                            a[2] == 'i' &&
                            a[3] == 'p')
                        {
                            return true;
                        }
                        else
                        {
                            if (a.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
             * */

            return encoding;
        }


        /// <summary>
        /// A fast way to check if gzip compression is supported
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsGZipSupported(HttpRequest request)
        {

            NameValueCollection n = request.Headers;

            for (int i = 0; i < n.Count; i++)
            {
                string h = n.GetKey(i);
                if (h.Length == 15 &&
                    h[0] == 'A' &&
                    h[1] == 'c' &&
                    h[2] == 'c' &&
                    h[3] == 'e' &&
                    h[4] == 'p' &&
                    h[5] == 't' &&
                    h[6] == '-' &&
                    h[7] == 'E' &&
                    h[8] == 'n' &&
                    h[9] == 'c' &&
                    h[10] == 'o' &&
                    h[11] == 'd' &&
                    h[12] == 'i' &&
                    h[13] == 'n' &&
                    h[14] == 'g')
                {

                    string a = n.Get(i);
                    if (a.Length >= 4)
                    {
                        if (a[0] == 'g' &&
                            a[1] == 'z' &&
                            a[2] == 'i' &&
                            a[3] == 'p')
                        {
                            return true;
                        }
                        else
                        {
                            if (a.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            return false;


        }


        /// <summary>
        /// get the http method: GET or POST
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static HttpMethod GetHttpMethod(HttpRequest request)
        {
            if (request.HttpMethod[0] == 'P')
            {
                return HttpMethod.POST;
            }
            else if (request.HttpMethod[0] == 'G')
            {
                return HttpMethod.GET;
            }

            return HttpMethod.Unknown;
        }


        /*
        /// <summary>
        /// Get the input content type
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static HttpRequestContentType GetContentType(HttpRequest request)
        {
            // If it's "GET" method, then the input is part of the query string.
            if (request.HttpMethod[0] == 'G' || request.HttpMethod[0] == 'g')
            {
                if (request.QueryString.Count > 0)
                    return HttpRequestContentType.QueryString;
                else
                    return HttpRequestContentType.None;
            }
            // If it's "POST" method, then the input is part of the body
            else if (request.HttpMethod[0] == 'P' || request.HttpMethod[0] == 'p')
            {
                if (request.InputStream.Length > 0)
                {
                    if (request.Form.Count > 0)
                        return HttpRequestContentType.Form;
                    else
                        return HttpRequestContentType.Json;
                }
                else
                {
                    return HttpRequestContentType.None;
                }

                /*
                var headers = request.Headers;
                for (int i = 0; i < headers.Count; i++)
                {
                    string key = headers.GetKey(i);
                    if (key.Length == 12 &&
                        key[0] == 'C' &&
                        key[1] == 'o' &&
                        key[2] == 'n' &&
                        key[3] == 't' &&
                        key[4] == 'e' &&
                        key[5] == 'n' &&
                        key[6] == 't' &&
                        key[7] == '-' &&
                        key[8] == 'T' &&
                        key[9] == 'y' &&
                        key[10] == 'p' &&
                        key[11] == 'e')
                    {
                        string value = headers.Get(i);
                        if (value.IndexOf("json", StringComparison.OrdinalIgnoreCase) != -1)
                        {
                            // If Content-Type is "application/json", inputs are stored in HttpRequest.InputStream
                            return HttpRequestContentType.Json;
                        }
                        else if (value.IndexOf("form", StringComparison.OrdinalIgnoreCase) != -1)
                        {
                            // If Content-Type is "application/x-www-form-urlencoded", inputs are stored in HttpRequest.Form
                            return HttpRequestContentType.Form;
                        }
                        break;
                    }
                }
                 
            }

            return HttpRequestContentType.Unknown;
        }

*/
        /// <summary>
        /// read input
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetInput(HttpRequest request)
        {
            string input = string.Empty;
            TextReader tr = new StreamReader(request.InputStream);
            try
            {
                input = tr.ReadToEnd();
            }
            finally
            {
                tr.Close();
            }
            return input;
        }
    }
}
